package com.rahwi.rahwi_server.Service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rahwi.rahwi_server.DAO.UserDAO;
import com.rahwi.rahwi_server.Entity.User;
import com.rahwi.rahwi_server.Service.Interface.IUserService;
import com.rahwi.rahwi_server.Utils.token.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName UserService
 * @Description
 * @Date 2021/12/12 14:16
 * @Autor mjw
 * @Version 1.0
 */

@Service
public class UserService implements IUserService {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private JWTutil jwTutil;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public User getUserById(int id) {
        return userDAO.getOne(id);
    }

    @Override
    public Optional<User> getUserByEmail(String email) {
        Specification<User> specification = (Specification<User>)
                (root, criteriaQuery, criteriaBuilder) ->
                        criteriaBuilder.equal(root.get("Email"), email);
        return userDAO.findOne(specification);
    }

    @Override
    public List<User> getUserByName(String name) {
        Specification<User> specification = (Specification<User>)
                        (root, criteriaQuery, criteriaBuilder) ->
                        criteriaBuilder.equal(root.get("UserName"), name);
        return userDAO.findAll(specification);
    }

    /**
     * 根据token获取用户信息
     * 需要先验证token合法性
     * 再从redis中取userid
     * @param token
     * @return
     */
    @Override
    public User getUserByToken(String token) {
        if(token == null || token.isBlank() || jwTutil.checkToken(token) == null){
            return null;
        }
        else {
            String value = redisTemplate.boundValueOps("TOKEN_"+token).get();
            try {
                return value == null ? null : new ObjectMapper().readValue(value,User.class);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    @Override
    public void saveUser(User user) {
        userDAO.save(user);
    }

    @Override
    public void deleteUser(User user) {
        userDAO.save(user);
    }

    @Override
    public void modifyUser(User user) {
        userDAO.deleteById(user.getUserId());
    }

    public int findAll() { return userDAO.findAll().size(); }
}
